from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView, ListCreateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer, AdminRenderer
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.decorators import api_view, permission_classes
from django.contrib.auth.models import User
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth import authenticate, logout
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from rest_framework_simplejwt.tokens import RefreshToken
from crm.models import (
        Company, Customers, Opportunity, Companydept, Employee, Account,
        Contact, BizOpp, Deal, Communication
    )
from crm.serializers import (
    CompanydeptSerializer,
    EmployeeSerializer,
    AccountSerializer,
    AccountRelativeSerializer,
    ContactDetailSerializer,
    ContactListSerializer,
    ContactCreateSerializer,
    ContactUpdateSerializer,
    BizOppListSerializer,
    BizOppCreateSerializer,
    BizOppUpdateSerializer,
    BizOppSerializer,
    UserSerializer,
    DealSerializer,
    CommunicationSerializer,
    )
from crm.paginators import StandardResultsSetPagination
from django.db.models import Q
from django.contrib.auth.decorators import permission_required
from django.core.exceptions import PermissionDenied

# Create your views here.

# 公司部门
class DeptViewSet(ModelViewSet):
    queryset = Companydept.objects.all()    
    serializer_class = CompanydeptSerializer
    renderer_classes = [BrowsableAPIRenderer,JSONRenderer]
    pagination_class = StandardResultsSetPagination
    permission_classes = [IsAuthenticated]

# 员工信息
class EmployeeListView(ListCreateAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer
    renderer_classes = [BrowsableAPIRenderer,JSONRenderer]
    permission_classes = [IsAuthenticated]
    pagination_class = StandardResultsSetPagination


    def get_queryset(self):
        # 检查用户权限, 如果用户没有权限，则拒绝访问，发
        user = self.request.user
        if not user.has_perm("crm.view_employee"):
            print("没有权限，",self.request.get_full_path())
            raise PermissionDenied("没有权限")
        qs = Employee.objects.all()
        if 'name' in self.request.query_params:
            q_name = self.request.query_params['name']
            qs = qs.filter(name__icontains=q_name)
        return qs

    def get_object(self):
        #检查用户权限，如果用户没有权限，抛出PermissionDenied异常后返回
        #否则，返回查询到的对象
        user = self.request.user
        if not user.has_perm("crm.add_employee"):
            print("没有权限，",self.request.get_full_path())
            raise PermissionDenied("没有权限")
        return super().get_object()

class EmployeeDetailView(RetrieveUpdateDestroyAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer
    renderer_classes = [BrowsableAPIRenderer,JSONRenderer]
    permission_classes = [IsAuthenticated]

    def get_object(self):
        #检查用户权限，如果用户没有权限，抛出PermissionDenied异常后返回
        #否则，返回查询到的对象
        user = self.request.user
        if not (user.has_perm("crm.change_employee") and user.has_perm("crm.delete_employee")):
            print("没有权限，",self.request.get_full_path())
            raise PermissionDenied("没有权限")
        return super().get_object()


# viewset for Account model 
class AccountViewSet(ModelViewSet):
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    renderer_classes = [BrowsableAPIRenderer,JSONRenderer]
    pagination_class = StandardResultsSetPagination
    permission_classes = [IsAuthenticated]

# Viewset class for Contact model 
class ContactViewSet(ModelViewSet):
    queryset = Contact.objects.all()
    renderer_classes = [BrowsableAPIRenderer,JSONRenderer]
    pagination_class = StandardResultsSetPagination
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        # 根据不同的action, 返回相应的serializer class
        if self.action == 'list' :
            return ContactListSerializer
        elif self.action == 'create' :
            return ContactCreateSerializer
        elif self.action == 'update':
            return ContactUpdateSerializer
        elif self.action == 'retrieve':
            return ContactDetailSerializer
        else:
            return ContactDetailSerializer

class OpportunityViewSet(ModelViewSet):
    queryset = Opportunity.objects.all()
    renderer_classes = [BrowsableAPIRenderer,JSONRenderer]
    pagination_class = StandardResultsSetPagination
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        # 根据不同的action, 返回相应的serializer class
        if self.action == 'list' :
            return BizOppListSerializer
        elif self.action == 'create' :
            return BizOppCreateSerializer
        elif self.action == 'update':
            return BizOppUpdateSerializer
        elif self.action == 'retrieve':
            return BizOppSerializer
        else:
            return BizOppSerializer

class DealViewSet(ModelViewSet):
    queryset = Deal.objects.all()
    serializer_class = DealSerializer
    renderer_classes = [BrowsableAPIRenderer,JSONRenderer]
    pagination_class = StandardResultsSetPagination
    permission_classes = [IsAuthenticated]


class CommunicationViewSet(ModelViewSet):
    queryset = Communication.objects.all()
    serializer_class = CommunicationSerializer
    renderer = [BrowsableAPIRenderer,JSONRenderer]
    pagination_class = StandardResultsSetPagination
    permission_classes = [IsAuthenticated]


# Login view with jwt token
# return access and refresh token after login. 
# logout API is not needed for jwt token, logout is done by frontend locally. 

def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)
    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

@api_view(['POST'])
def user_login(request):
    username = request.data.get('username')
    passwd = request.data.get('password')
    try: 
        user = authenticate(username=username, password=passwd)
    except ObjectDoesNotExist:
        return Response({"error": "用户名或密码错误"}, status=status.HTTP_400_BAD_REQUEST)

    if user:
        tokens = get_tokens_for_user(user)
        return Response(tokens, status=status.HTTP_200_OK)
    
    return Response({"error": "Invalid username or password"}, status=status.HTTP_400_BAD_REQUEST)

